package cn.tips.dmp.supports.helper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 常用工具类
 *
 * @author pkb
 */
@Slf4j
public class CommonRequestHelper {

    /**
     * ajax请求头名
     */
    private final static String X_REQUESTED_WITH_STRING = "X-Requested-With";

    /**
     * ajax请求头内容
     */
    private final static String XML_HTTP_REQUEST_STRING = "XMLHttpRequest";

    /**
     * 获取当前请求的URI地址
     *
     * @return URI地址
     */
    public static String getCurrentRequestUri() {
        HttpServletRequest servletRequest = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        return servletRequest.getRequestURI();
    }

    /**
     * 判断是否是ajax请求
     *
     * @param httpServletRequest 请求
     * @return 执行结果
     */
    public static boolean isAjax(HttpServletRequest httpServletRequest) {
        String header = httpServletRequest.getHeader(X_REQUESTED_WITH_STRING);
        if (XML_HTTP_REQUEST_STRING.equalsIgnoreCase(header)) {
            log.debug("请求判断:当前请求[{}]为Ajax请求", httpServletRequest.getRequestURI());
            return Boolean.TRUE;
        }
        log.debug("请求判断:当前请求[{}]为非Ajax请求", httpServletRequest.getRequestURI());
        return Boolean.FALSE;
    }

}
